package com.zhtools.wx.bean;

import com.zhtools.wx.WXPayRequestParams;
import com.zhtools.wx.exception.WXPayException;
import com.zhtools.wx.utils.WXPayUtil;
import com.zhtools.wx.utils.WXUtil;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhanghao
 * 退款申请请求参数
 */
public class FefundRequest implements WXPayRequestParams, Serializable {
    private static final long serialVersionUID = -6740146669761578245L;
    private static final String PATTERN = "#";
    private static final String EMPTY_STRING = "";
    private static final String TRANSFORM_EXCEPTION = "转换微信支付退款申请接口请求报文异常";

    private String outTradeNo;
    private String outRefundNo;
    private Integer totalFee;
    private Integer refundFee;

    public String getOutTradeNo() {
        return outTradeNo;
    }

    public void setOutTradeNo(String outTradeNo) {
        this.outTradeNo = outTradeNo;
    }

    public String getOutRefundNo() {
        return outRefundNo;
    }

    public void setOutRefundNo(String outRefundNo) {
        this.outRefundNo = outRefundNo;
    }

    public Integer getTotalFee() {
        return totalFee;
    }

    public void setTotalFee(Integer totalFee) {
        this.totalFee = totalFee;
    }

    public Integer getRefundFee() {
        return refundFee;
    }

    public void setRefundFee(Integer refundFee) {
        this.refundFee = refundFee;
    }

    @Override
    public String toString() {
        return "FefundRequest{" +
                "outTradeNo='" + outTradeNo + '\'' +
                ", outRefundNo='" + outRefundNo + '\'' +
                ", totalFee=" + totalFee +
                ", refundFee=" + refundFee +
                '}';
    }

    @Override
    public String toXml(String appId, String mchId, String signKey) throws WXPayException {
        return toXml(appId,mchId,null,signKey);
    }

    @Override
    public String toXml(String appId, String mchId, String notifyUrl, String signKey) throws WXPayException {
        String nonce_str = WXUtil.generateNonceStr();
        DecimalFormat decimalFormat = new DecimalFormat(PATTERN);

        Map<String, String> params = new HashMap<>();
        params.put("appid", appId);
        params.put("mch_id", mchId);
        params.put("nonce_str", nonce_str);
        params.put("out_trade_no", this.outTradeNo);
        params.put("out_refund_no", this.outRefundNo);
        params.put("total_fee", decimalFormat.format(this.totalFee));
        params.put("refund_fee", decimalFormat.format(this.refundFee));

        String requestXml = EMPTY_STRING;
        try {
            requestXml = WXPayUtil.generateSignedXml(params, signKey);
        } catch (Exception e) {
            throw new WXPayException(TRANSFORM_EXCEPTION, e);
        }
        return requestXml;
    }
}
